package com.xyulu.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.xyulu.entity.common.MessageConstant;
import com.xyulu.entity.common.Result;
import com.xyulu.entity.vo.LoginUser;
import com.xyulu.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 系统常用方法控制器
 * @Author luming
 * @Date 2021/3/3
 * @Version 1.0
 */
@Controller
@RequestMapping("/common")
public class CommonController {

    @GetMapping("/toLogin")
    public String toSystemLogin(){
        return "system/login";
    }

    @Resource
    private SysUserService userService;

    /**
     * 登录接口
     * @param loginUser 登录信息封装
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody LoginUser loginUser,
                        HttpServletRequest request){
        //验证码校验
        if (!CaptchaUtil.ver(loginUser.getCaptcha(), request)) {
            //清除Session中的验证码
            CaptchaUtil.clear(request);
            return new Result(400, MessageConstant.CAPTCHA_ERROR);
        }
        return userService.login(loginUser);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    @ResponseBody
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Result(200,MessageConstant.LOGOUT_SUCCESS);
    }

    /**
     * 获取验证码图片
     * @param request  the request
     * @param response the response
     * @throws IOException the io exception
     */
    @RequestMapping("/getCaptcha")
    @ResponseBody
    public void getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SpecCaptcha captcha = new SpecCaptcha(130, 48);
        captcha.setLen(4);
        CaptchaUtil.out(captcha, request, response);
    }

}
